﻿using BomComparison.Core.Model;

namespace BomComparison.Algorithm.Comparers;
public static class PartReferenceComparer
{

    public static PartReferenceDiff Compare(string source, string target)
    {
        // 统一将 null 转为空字符串，避免后续判空
        source ??= string.Empty;
        target ??= string.Empty;

        // 转换为 HashSet，保证非 null
        var sourceSet = PartReferenceParser.StringToHashSet(source) ?? new HashSet<string>();
        var targetSet = PartReferenceParser.StringToHashSet(target) ?? new HashSet<string>();

        var result = new PartReferenceDiff();

        // 计算新增和删除的位号
        var added = targetSet.Except(sourceSet).ToList();
        var deleted = sourceSet.Except(targetSet).ToList();

        result.Added = added.Count > 0 ? string.Join(",", added) : string.Empty;
        result.Deleted = deleted.Count > 0 ? string.Join(",", deleted) : string.Empty;

        // 可选：自动设置变更类型
        //if (added.Count == 0 && deleted.Count == 0)
        //    result.PartReferenceDiffType = PartReferenceDiffType.None;
        //else if (added.Count > 0 && deleted.Count == 0)
        //    result.PartReferenceDiffType = PartReferenceDiffType.Added;
        //else if (added.Count == 0 && deleted.Count > 0)
        //    result.PartReferenceDiffType = PartReferenceDiffType.Deleted;
        //else
        //    result.PartReferenceDiffType = PartReferenceDiffType.Modified;

        return result;
    }

    public static bool IsSameReferenceSet(HashSet<string> set1, HashSet<string> set2)
    {
        return set1.SetEquals(set2);
    }

    public static bool IsSameReference(string source, string target)
    {
        var sourceList = PartReferenceParser.StringToHashSet(source);
        var targetList = PartReferenceParser.StringToHashSet(target);

        return sourceList.SetEquals(targetList);
    }

    public static bool Equals(List<string> source, List<string> target)
    {


        return !source.Except(target).Any() && !target.Except(source).Any();
    }

    public static int GetHashCode(List<string> obj)
    {
        unchecked // Overflow is fine, just wrap
        {
            var hash = 19;
            foreach (var item in obj.OrderBy(s => s)) // Order by the strings to ensure consistent hash code
            {
                hash = hash * 31 + item.GetHashCode();
            }
            return hash;
        }
    }
}


